import { computed, ref } from 'vue'

export default function useShortCut (props, groupRef) {
  const ANCHOR_HEIGHT = 18
  const scrollRef = ref(null)
  const touch = {}
  const shortcutList = computed(() => {
    return props.data.map((item) => {
      return item.title
    })
  })

  function shortcutTouchStart (e) {
    const anchorIndex = parseInt(e.target.dataset.index)
    touch.y1 = e.touches[0].pageY
    touch.index = anchorIndex
    scrollTo(anchorIndex, 0)
  }

  function shortcutTouchMove (e) {
    touch.y2 = e.touches[0].pageY
    const delta = touch.y2 - touch.y1
    const moveIndex = Math.floor(delta / ANCHOR_HEIGHT)
    scrollTo(moveIndex + touch.index, 0)
  }

  function scrollTo (index) {
    if (isNaN(index)) return
    index = Math.max(0, Math.min(shortcutList.value.length - 1, index))
    const targetEl = groupRef.value.children[index]
    const scroll = scrollRef.value.scroll
    scroll.scrollToElement(targetEl, 0)
  }

  return {
    shortcutList,
    scrollRef,
    shortcutTouchStart,
    shortcutTouchMove
  }
}
